<!DOCTYPE HTML>
<html lang="zh-Hans" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>数据库表达式执行的黑魔法：与Rust编译器斗智斗勇之表达式向量化 Part 5 &amp; 6 - Rust 优秀博文</title>


        <!-- Custom HTML head -->
        
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="../../favicon.svg">
        <link rel="shortcut icon" href="../../favicon.png">
        <link rel="stylesheet" href="../../css/variables.css">
        <link rel="stylesheet" href="../../css/general.css">
        <link rel="stylesheet" href="../../css/chrome.css">
        <link rel="stylesheet" href="../../css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="../../fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="../../highlight.css">
        <link rel="stylesheet" href="../../tomorrow-night.css">
        <link rel="stylesheet" href="../../ayu-highlight.css">

        <!-- Custom theme stylesheets -->

    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "../../";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">1.</strong> 类型系统</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../01_类型系统/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow.html"><strong aria-hidden="true">1.1.</strong> Rust Concept Clarification Deref vs AsRef vs Borrow vs Cow</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow/Deref_AsRef_Borrow_Cow释义.html"><strong aria-hidden="true">1.2.</strong> Deref AsRef Borrow Cow 释义</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然/Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然.html"><strong aria-hidden="true">1.3.</strong> Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust的Cow类型有什么用？详解Cow及其用途/Rust的Cow类型有什么用？详解Cow及其用途.html"><strong aria-hidden="true">1.4.</strong> Rust的Cow类型有什么用？详解Cow及其用途</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/判别Fn、FnMut、FnOnce的标准/判别Fn、FnMut、FnOnce的标准.html"><strong aria-hidden="true">1.5.</strong> 判别Fn、FnMut、FnOnce的标准</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/一行代码告诉你内部可变性的真相(UnsafeCell)/一行代码告诉你内部可变性的真相(UnsafeCell).html"><strong aria-hidden="true">1.6.</strong> 一行代码告诉你内部可变性的真相(UnsafeCell)</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Tour_of_Rust's_Standard_Library_Traits/Tour_of_Rust's_Standard_Library_Traits.html"><strong aria-hidden="true">1.7.</strong> Tour of Rust's Standard Library Traits</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/逆变、协变与子类型，以及Rust/逆变、协变与子类型，以及Rust.html"><strong aria-hidden="true">1.8.</strong> 逆变、协变与子类型，以及Rust</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust自引用结构、Pin与Unpin/Rust自引用结构、Pin与Unpin.html"><strong aria-hidden="true">1.9.</strong> Rust自引用结构、Pin与Unpin</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/为什么Rust需要Pin,Unpin/为什么Rust需要Pin,Unpin.html"><strong aria-hidden="true">1.10.</strong> 译：为什么 Rust 需要 Pin, Unpin ？</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/定海神针Pin和Unpin/定海神针Pin和Unpin.html"><strong aria-hidden="true">1.11.</strong> 译：定海神针 Pin 和 Unpin</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/sizedness-in-rust/sizedness-in-rust.html"><strong aria-hidden="true">1.12.</strong> Sizedness in Rust</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust生命周期集大成者PhantomData〈T〉/Rust生命周期集大成者PhantomData〈T〉.html"><strong aria-hidden="true">1.13.</strong> Rust生命周期集大成者 PhantomData&lt;T&gt;</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操_Part_0.html"><strong aria-hidden="true">1.14.</strong> 数据库表达式执行的黑魔法：用Rust做类型体操 Part 0</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：GAT实现引用类型关联_Part_1.html"><strong aria-hidden="true">1.15.</strong> 数据库表达式执行的黑魔法：GAT实现引用类型关联 Part 1</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用HRTB写bound_Part_2.html"><strong aria-hidden="true">1.16.</strong> 数据库表达式执行的黑魔法：用HRTB写bound Part 2</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码_Part_3_&_4.html"><strong aria-hidden="true">1.17.</strong> 数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码 Part 3 & 4</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：与Rust编译器斗智斗勇之表达式向量化_Part_5_&_6.html" class="active"><strong aria-hidden="true">1.18.</strong> 数据库表达式执行的黑魔法：与Rust编译器斗智斗勇之表达式向量化 Part 5 & 6</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型_Part_7.html"><strong aria-hidden="true">1.19.</strong> 数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型 Part 7</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">2.</strong> 生命周期</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../02_生命周期/Rust中的生命周期——从StrSplit实例说开去/Rust中的生命周期——从StrSplit实例说开去.html"><strong aria-hidden="true">2.1.</strong> Rust中的生命周期——从StrSplit实例说开去</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/与ChatGPT深度对话来学Rust生命周期/与ChatGPT深度对话来学Rust生命周期.html"><strong aria-hidden="true">2.2.</strong> 与ChatGPT深度对话来学Rust生命周期</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——early_bound与late_bound（1）/进击的Rust生命周期——early_bound与late_bound（1）.html"><strong aria-hidden="true">2.3.</strong> 进击的Rust生命周期——early_bound与late_bound（1）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——early_bound与late_bound（2）/进击的Rust生命周期——early_bound与late_bound（2）.html"><strong aria-hidden="true">2.4.</strong> 进击的Rust生命周期——early_bound与late_bound（2）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——一力降十会的MIR（1）/进击的Rust生命周期——一力降十会的MIR（1）.html"><strong aria-hidden="true">2.5.</strong> 进击的Rust生命周期——一力降十会的MIR（1）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——一力降十会的MIR（2）/进击的Rust生命周期——一力降十会的MIR（2）.html"><strong aria-hidden="true">2.6.</strong> 进击的Rust生命周期——一力降十会的MIR（2）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/Common_Rust_Lifetime_Misconceptions/Common_Rust_Lifetime_Misconceptions.html"><strong aria-hidden="true">2.7.</strong> Common Rust Lifetime Misconceptions</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/Rust生命周期常见误区/Rust生命周期常见误区.html"><strong aria-hidden="true">2.8.</strong> 译：Rust生命周期常见误区</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">3.</strong> 无畏并发</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../05_无畏并发/简单写个Rust无锁队列/简单写个Rust无锁队列.html"><strong aria-hidden="true">3.1.</strong> 简单写个Rust无锁队列</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——混合自旋锁/进击的Rust多线程——混合自旋锁.html"><strong aria-hidden="true">3.2.</strong> 进击的Rust多线程——混合自旋锁</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/An_unsafe_tour_of_Rust's_Send_and_Sync/An_unsafe_tour_of_Rust's_Send_and_Sync.html"><strong aria-hidden="true">3.3.</strong> An unsafe tour of Rust's Send and Sync</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——Send与Sync/进击的Rust多线程——Send与Sync.html"><strong aria-hidden="true">3.4.</strong> 进击的Rust多线程——Send与Sync</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——离经叛道的PhantomData/进击的Rust多线程——离经叛道的PhantomData.html"><strong aria-hidden="true">3.5.</strong> 进击的Rust多线程——离经叛道的PhantomData</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust_Async_Pin概念解析/Rust_Async_Pin概念解析.html"><strong aria-hidden="true">3.6.</strong> Rust Async: Pin概念解析</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust和C++的并发库对比/Rust和C++的并发库对比.html"><strong aria-hidden="true">3.7.</strong> 译：Rust 和 C++ 的并发库对比</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust原子类型和内存排序/Rust原子类型和内存排序.html"><strong aria-hidden="true">3.8.</strong> Rust原子类型和内存排序</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">4.</strong> 网络编程</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../06_网络编程/从编解码层面理解WebSocket_手写一个WebSocket/从编解码层面理解WebSocket_手写一个WebSocket.html"><strong aria-hidden="true">4.1.</strong> 从编解码层面理解WebSocket 手写一 个WebSocket</a></li><li class="chapter-item expanded "><a href="../../06_网络编程/透过Rust探索系统的本原：网络篇/透过Rust探索系统的本原：网络篇.html"><strong aria-hidden="true">4.2.</strong> 透过Rust探索系统的本原：网络篇</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">5.</strong> 轮子系列</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../07_轮子系列/700行Rust写一个内存分配器/700行Rust写一个内存分配器.html"><strong aria-hidden="true">5.1.</strong> 700行Rust写一个内存分配器</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/Rust：网络库的实现思路/Rust：网络库的实现思路.html"><strong aria-hidden="true">5.2.</strong> Rust：网络库的实现思路</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/Rust异步运行时基础部件/Rust异步运行时基础部件.html"><strong aria-hidden="true">5.3.</strong> Rust异步运行时基础部件</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（1）.html"><strong aria-hidden="true">5.4.</strong> 使用Rust+epoll编写异步IO框架（1）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（2）.html"><strong aria-hidden="true">5.5.</strong> 使用Rust+epoll编写异步IO框架（2）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（3）.html"><strong aria-hidden="true">5.6.</strong> 使用Rust+epoll编写异步IO框架（3）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day1.html"><strong aria-hidden="true">5.7.</strong> 用rust从零开发一套web框架：day1</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day2.html"><strong aria-hidden="true">5.8.</strong> 用rust从零开发一套web框架：day2</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day3.html"><strong aria-hidden="true">5.9.</strong> 用rust从零开发一套web框架：day3</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day4.html"><strong aria-hidden="true">5.10.</strong> 用rust从零开发一套web框架：day4</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day5.html"><strong aria-hidden="true">5.11.</strong> 用rust从零开发一套web框架：day5</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">6.</strong> 奇技淫巧</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Copy-On-Write是不是优化？/Copy-On-Write是不是优化？.html"><strong aria-hidden="true">6.1.</strong> 译：Copy-On-Write是不是优化？</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/揭秘神奇的Rust_Axum风格的函数实现/揭秘神奇的Rust_Axum风格的函数实现.html"><strong aria-hidden="true">6.2.</strong> 译：揭秘神奇的 Rust Axum 风格的函数实现</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/“变长参数”函数与回调/“变长参数”函数与回调.html"><strong aria-hidden="true">6.3.</strong> “变长参数”函数与回调</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Rust字符串格式化的幕后：format_args!()/Rust字符串格式化的幕后：format_args!().html"><strong aria-hidden="true">6.4.</strong> 译：Rust字符串格式化的幕后：format_args!()</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/给Rust带来一点C++特产/给Rust带来一点C++特产.html"><strong aria-hidden="true">6.5.</strong> 给Rust带来一点C++特产</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/一步步实现_Rust_Bevy_ECS_的_System_简化版本/一步步实现_Rust_Bevy_ECS_的_System_简化版本.html"><strong aria-hidden="true">6.6.</strong> 一步步实现 Rust Bevy ECS 的 System 简化版本</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples.html"><strong aria-hidden="true">6.7.</strong> Exploring Design Patterns in Rust with Algorithmic Trading Examples</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">7.</strong> 源码分析</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：bytes源码分析/Rust并发：bytes源码分析.html"><strong aria-hidden="true">7.1.</strong> Rust并发：bytes源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：标准库Arc源码分析/Rust并发：标准库Arc源码分析.html"><strong aria-hidden="true">7.2.</strong> Rust并发：标准库Arc源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：标准库sync_Once源码分析/Rust并发：标准库sync_Once源码分析.html"><strong aria-hidden="true">7.3.</strong> Rust并发：标准库sync::Once源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust源码阅读：引用计数Rc/Rust源码阅读：引用计数Rc.html"><strong aria-hidden="true">7.4.</strong> Rust源码阅读：引用计数Rc</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust源码阅读：Cell、RefCell与内部可变性/Rust源码阅读：Cell、RefCell与内部可变性.html"><strong aria-hidden="true">7.5.</strong> Rust源码阅读： Cell、RefCell与内部可变性</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/关于_Rust_的_UnsafeCell、Cell_与_RefCell/关于_Rust_的_UnsafeCell、Cell_与_RefCell.html"><strong aria-hidden="true">7.6.</strong> 关于 Rust 的 UnsafeCell、Cell 与 RefCell</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust_Async_async-stream源码分析/Rust_Async_async-stream源码分析.html"><strong aria-hidden="true">7.7.</strong> Rust Async: async-stream源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/走进Tokio的异步世界/走进Tokio的异步世界.html"><strong aria-hidden="true">7.8.</strong> 走进 Tokio 的异步世界</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/tokio.rs_runtime的实现/tokio.rs_runtime的实现.html"><strong aria-hidden="true">7.9.</strong> tokio.rs runtime 的实现</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_internals/Tokio_internals.html"><strong aria-hidden="true">7.10.</strong> Tokio internals</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_internals/译文：Tokio內部机制.html"><strong aria-hidden="true">7.11.</strong> 译：Tokio 内部机制</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust_Axum_HTTP_框架的架构分析/Rust_Axum_HTTP_框架的架构分析.html"><strong aria-hidden="true">7.12.</strong> Rust Axum HTTP 框架的架构分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/安利一个Rust_Game_Engine：Bevy--ECS部分/安利一个Rust_Game_Engine：Bevy--ECS部分.html"><strong aria-hidden="true">7.13.</strong> 安利一个Rust Game Engine：Bevy--ECS部分</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_解析之任务调度/Tokio_解析之任务调度.html"><strong aria-hidden="true">7.14.</strong> Tokio 解析之任务调度</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">8.</strong> 生态观察</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../11_生态观察/Rust_web_frameworks_have_subpar_error_reporting/Rust_web_frameworks_have_subpar_error_reporting.html"><strong aria-hidden="true">8.1.</strong> Rust web frameworks have subpar error reporting</a></li><li class="chapter-item expanded "><a href="../../11_生态观察/SeaORM：要做Rust版本的ActiveRecord/SeaORM：要做Rust版本的ActiveRecord.html"><strong aria-hidden="true">8.2.</strong> SeaORM：要做Rust版本的ActiveRecord</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">9.</strong> 死灵终极</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_总述.html"><strong aria-hidden="true">9.1.</strong> 译：Learn Rust the Dangerous Way 总述</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_0.html"><strong aria-hidden="true">9.2.</strong> 译：Learn Rust the Dangerous Way 0</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_1.html"><strong aria-hidden="true">9.3.</strong> 译：Learn Rust the Dangerous Way 1</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_2.html"><strong aria-hidden="true">9.4.</strong> 译：Learn Rust the Dangerous Way 2</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_3.html"><strong aria-hidden="true">9.5.</strong> 译：Learn Rust the Dangerous Way 3</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_4.html"><strong aria-hidden="true">9.6.</strong> 译：Learn Rust the Dangerous Way 4</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_5.html"><strong aria-hidden="true">9.7.</strong> 译：Learn Rust the Dangerous Way 5</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（一）.html"><strong aria-hidden="true">9.8.</strong> Unsafe Rust 随堂小测（一）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（二）.html"><strong aria-hidden="true">9.9.</strong> Unsafe Rust 随堂小测（二）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（三）.html"><strong aria-hidden="true">9.10.</strong> Unsafe Rust 随堂小测（三）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测参考答案.html"><strong aria-hidden="true">9.11.</strong> Unsafe Rust 随堂小测参考答案</a></li></ol></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">Rust 优秀博文</h1>

                    <div class="right-buttons">
                        <a href="../../print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="数据库表达式执行的黑魔法与-rust-编译器斗智斗勇之表达式向量化-part-5--6"><a class="header" href="#数据库表达式执行的黑魔法与-rust-编译器斗智斗勇之表达式向量化-part-5--6">数据库表达式执行的黑魔法：与 Rust 编译器斗智斗勇之表达式向量化 (Part 5 &amp; 6)</a></h1>
<p>作者：<a href="https://www.zhihu.com/people/skyzh">迟策</a></p>
<p>原载：<a href="https://zhuanlan.zhihu.com/p/461901665">https://zhuanlan.zhihu.com/p/461901665</a></p>
<p>这个系列的标题逐渐变得离谱起来 —— 从《用 Rust 做类型体操》到《与 Rust 编译器斗智斗勇》。这是因为我们在写 Rust 代码的时候所用的技巧也越来越高端了。</p>
<p>请注意：本文所提到的 bug 已经在最新版 Rust 编译器中修复。因此这两天的类型体操可以直接跳过了 :)</p>
<p>上篇：<a href="https://zhuanlan.zhihu.com/p/461657165">数据库表达式执行的黑魔法：用 Rust 做类型体操 (Part 3 &amp; 4)</a></p>
<p>下篇：<a href="https://zhuanlan.zhihu.com/p/463477290">数据库表达式执行的黑魔法：与 Rust 编译器斗智斗勇 (Part 7)</a></p>
<h2 id="day-5-表达式向量化-上"><a class="header" href="#day-5-表达式向量化-上">Day 5: 表达式向量化 (上)</a></h2>
<p>经过了整整四天的类型体操，我们终于可以做表达式向量化了：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let expr = BinaryExpression::&lt;StringArray, StringArray, BoolArray, _&gt;::new(str_contains);
// We only need to pass `ArrayImpl` to the expression, and it will do everything for us,
// including type checks, loopping, etc.
let result = expr.eval(/* &amp;ArrayImpl,  &amp;ArrayImpl */).unwrap();
<span class="boring">}
</span></code></pre></pre>
<p><code>BinaryExpression</code> 的向量化代码非常好写：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;I1: Array, I2: Array, O: Array&gt; BinaryExpression&lt;I1, I2, O&gt;
{
    /// Evaluate the expression with the given array.
    pub fn eval&lt;'a&gt;(&amp;self, i1: &amp;'a ArrayImpl, i2: &amp;'a ArrayImpl) -&gt; Result&lt;ArrayImpl&gt; {
        let i1a: &amp;'a I1 = i1.try_into()?;
        let i2a: &amp;'a I2 = i2.try_into()?;
        assert_eq!(i1.len(), i2.len(), &quot;array length mismatch&quot;);
        let mut builder: O::Builder = O::Builder::with_capacity(i1.len());
        for (i1, i2) in i1a.iter().zip(i2a.iter()) {
            match (i1, i2) {
                (Some(i1), Some(i2)) =&gt; builder.push(Some((self.func)(i1, i2).as_scalar_ref())),
                _ =&gt; builder.push(None),
            }
        }
        Ok(builder.finish().into())
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>但主要问题是：</p>
<ul>
<li><code>BinaryExpression</code> 结构体应该怎么定义？</li>
<li><code>self.func</code> 应该是什么类型？</li>
</ul>
<p>先考虑结构体怎么定义。理论上结构体里面只要存一个函数对象 (比如 <code>str_contains</code>) 就行了。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub struct BinaryExpression&lt;I1: Array, I2: Array, O: Array, F&gt; {
    func: F,
}
<span class="boring">}
</span></code></pre></pre>
<p>编译器无情打脸：</p>
<pre><code class="language-text">error[E0392]: parameter `O` is never used
  --&gt; archive/day5/src/expr.rs:23:51
   |
23 | pub struct BinaryExpression&lt;I1: Array, I2: Array, O: Array, F&gt; {
   |                                                   ^ unused parameter
   |
   = help: consider removing `O`, referring to it in a field, or using a marker such as `PhantomData`
   = help: if you intended `O` to be a const parameter, use `const O: usize` instead
</code></pre>
<p><code>PhantomData</code> 是个啥？这个和协变与 drop checker 有关，这里不再深入。总之，根据编译器的提示，我们需要把这些 generic parameter 都加进结构体：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub struct BinaryExpression&lt;I1: Array, I2: Array, O: Array, F&gt; {
    func: F,
    _phantom: PhantomData&lt;(I1, I2, O)&gt;,
}
<span class="boring">}
</span></code></pre></pre>
<p>接下来考虑 <code>func</code> 的类型。想到 <code>str_contains</code> 函数的签名：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub fn str_contains(i1: &amp;str, i2: &amp;str) -&gt; bool {
    i1.contains(i2)
}
<span class="boring">}
</span></code></pre></pre>
<p>推广之，则可以写出对应的 Fn trait：</p>
<pre><code class="language-text">F: Fn(I1::RefItem&lt;'a&gt;, I2::RefItem&lt;'a&gt;) -&gt; O::OwnedItem
</code></pre>
<p>在 <code>impl BinaryExpression</code> 的时候，我们必然要提供一个 lifetime parameter。这个参数可以在 impl 的时候指定：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;'a, I1: Array, I2: Array, O: Array, F&gt; BinaryExpression&lt;I1, I2, O, F&gt;
where
    &amp;'a I1: TryFrom&lt;&amp;'a ArrayImpl, Error = TypeMismatch&gt;,
    &amp;'a I2: TryFrom&lt;&amp;'a ArrayImpl, Error = TypeMismatch&gt;,
    F: Fn(I1::RefItem&lt;'a&gt;, I2::RefItem&lt;'a&gt;) -&gt; O::OwnedItem,
{
    pub fn new(func: F) -&gt; Self {
        Self {
            func,
            _phantom: PhantomData,
        }
    }
    
    // ...
}
<span class="boring">}
</span></code></pre></pre>
<p>最后跑一下编译测试：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[test]
fn test_str_contains() {
    let expr = BinaryExpression::&lt;StringArray, StringArray, BoolArray, _&gt;::new(str_contains);
    let result = expr.eval(&amp;test_array(), &amp;test_array()).unwrap();
}
<span class="boring">}
</span></code></pre></pre>
<p>大功告成！通过一个简单的 <code>BinaryExpression</code> struct，我们就可以直接将普通函数向量化了。</p>
<h2 id="day-6-表达式向量化-下"><a class="header" href="#day-6-表达式向量化-下">Day 6: 表达式向量化 (下)</a></h2>
<p>事情往往没有这么简单。在实际的表达式执行中，开发者通常会写出这样的逻辑：</p>
<ul>
<li>根据收到的 SQL Plan 创建表达式对象。</li>
<li>从存储捞 Array 然后执行表达式。</li>
</ul>
<p>写成 Rust 代码，大概是这个样子：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let expr = build_expression(prost_message);
let l = storage.get_data();
let r = storage.get_data();
let result = expr.eval(&amp;l, &amp;r).unwrap();
<span class="boring">}
</span></code></pre></pre>
<p>这个 <code>build_expression</code> 函数应该怎么写捏？我们以返回向量化 <code>cmp_ge</code> 函数的表达式为例：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/// Return if `i1 &gt; i2`. Note that `i1` and `i2` could be different types. This
/// function will automatically cast them into `C` type.
///
/// * `I1`: left input type.
/// * `I2`: right input type.
/// * `C`: cast type.
pub fn cmp_ge&lt;'a, I1: Array, I2: Array, C: Array + 'static&gt;(
    i1: I1::RefItem&lt;'a&gt;,
    i2: I2::RefItem&lt;'a&gt;,
) -&gt; bool
where
    I1::RefItem&lt;'a&gt;: Into&lt;C::RefItem&lt;'a&gt;&gt;,
    I2::RefItem&lt;'a&gt;: Into&lt;C::RefItem&lt;'a&gt;&gt;,
    C::RefItem&lt;'a&gt;: PartialOrd,
{
    i1.into().partial_cmp(&amp;i2.into()).unwrap() == Ordering::Greater
}

fn create_expression(
) -&gt; BinaryExpression&lt;StringArray, StringArray, BoolArray, impl Fn(&amp;str, &amp;str) -&gt; bool&gt; {
    BinaryExpression::&lt;StringArray, StringArray, BoolArray, _&gt;::new(
        cmp_ge::&lt;StringArray, StringArray, StringArray&gt;,
    )
}
<span class="boring">}
</span></code></pre></pre>
<p>尝试编译一下，编译器报了一个神奇的错：</p>
<pre><code class="language-text">error: implementation of `FnOnce` is not general enough
   --&gt; archive/day5/src/expr.rs:101:10
    |
101 |     ) -&gt; BinaryExpression&lt;StringArray, StringArray, BoolArray, impl Fn(&amp;str, &amp;str) -&gt; bool&gt; {
    |          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ implementation of `FnOnce` is not general enough
    |
    = note: `fn(&lt;string_array::StringArray as array::Array&gt;::RefItem&lt;'_&gt;, &lt;string_array::StringArray as array::Array&gt;::RefItem&lt;'_&gt;) -&gt; bool {expr::cmp::cmp_ge::&lt;'_, string_array::StringArray, string_array::StringArray, string_array::StringArray&gt;}` must implement `FnOnce&lt;(&amp;str, &amp;'0 str)&gt;`, for any lifetime `'0`...
    = note: ...but it actually implements `FnOnce&lt;(&amp;'1 str, &amp;'1 str)&gt;`, for some specific lifetime `'1`
</code></pre>
<p>而如果是直接调用不带泛型的标量函数（比如 <code>str_contains</code>）：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn create_expression(
) -&gt; BinaryExpression&lt;StringArray, StringArray, BoolArray, impl Fn(&amp;str, &amp;str) -&gt; bool&gt; {
    BinaryExpression::&lt;StringArray, StringArray, BoolArray, _&gt;::new(str_contains)
}
<span class="boring">}
</span></code></pre></pre>
<p>则一点问题也没有。</p>
<p>为什么捏？感觉这就和 GAT 下的生命周期表达有关系了。</p>
<p>首先分析一下编译错误信息，对于 <code>cmp_ge</code> 的报错，</p>
<pre><code class="language-text">= note: `fn(&lt;string_array::StringArray as array::Array&gt;::RefItem&lt;'_&gt;, &lt;string_array::StringArray as array::Array&gt;::RefItem&lt;'_&gt;) -&gt; bool {expr::cmp::cmp_ge::&lt;'_, string_array::StringArray, string_array::StringArray, string_array::StringArray&gt;}` must implement `FnOnce&lt;(&amp;str, &amp;'0 str)&gt;`, for any lifetime `'0`...
    = note: ...but it actually implements `FnOnce&lt;(&amp;'1 str, &amp;'1 str)&gt;`, for some specific lifetime `'1`
</code></pre>
<p>意思是 <code>cmp_ge</code> 的两个参数，生命周期是<strong>一个</strong>指定的 <code>'a</code>；而这里如果要作为 <code>create_expression</code> 的返回值，要求 <code>cmp_ge</code> 对于所有生命周期都成立。</p>
<p>也就是说，对于 <code>contains_str</code> 这个函数，编译器可以在任何地方都推导出它对于所有生命周期都成立；而对于 <code>cmp_ge</code> 这个函数，编译器在函数体返回值的地方无法推导出它对于所有生命周期都成立，于是给它绑定了一个特定的生命周期 <code>'a</code>。感觉这是一个比较难解决的编译器 bug。</p>
<p>那我们能不能把这个 <code>for&lt;'a&gt;</code> 的性质强行写进函数签名里呢？</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn create_expression(
) -&gt; BinaryExpression&lt;StringArray, StringArray, BoolArray, impl Fn(&amp;str, &amp;str) -&gt; bool&gt; {
    /* NOTE: THIS CODE WON'T COMPILE! */
    BinaryExpression::&lt;for&lt;'a&gt;, StringArray, StringArray, BoolArray, _&gt;::new(str_contains)
}
<span class="boring">}
</span></code></pre></pre>
<p>很显然，Rust 没法表达这种性质。因此，我们必须想办法把 <code>BinaryExpression</code> 里面的生命周期去掉，从而在这里让编译器能够推导出 <code>cmp_ge</code> 这个泛型函数对“所有生命周期”都成立。</p>
<p>在 type-exercise 仓库里，我提供了两种办法：</p>
<ul>
<li>the easy way – 把所有函数都实现成结构体，函数体内的生命周期和 <code>&amp;self</code> 一致，规避这些问题。缺点是开发者得把所有标量函数写成结构体，有点麻烦。</li>
<li>the hard way – 想办法证明所有的符合签名的标量函数都有 “for all lifetime” 的性质。</li>
</ul>
<p>这篇文章就会着重分析如何一步步证明函数的性质，并去掉生命周期。</p>
<h3 id="证明泛型标量函数对所有生命周期成立"><a class="header" href="#证明泛型标量函数对所有生命周期成立">证明泛型标量函数对所有生命周期成立</a></h3>
<p>在实现 <code>cmp_ge</code> 的时候，有一个很讨厌的点：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn cmp_ge&lt;'a, I1: Array, I2: Array, C: Array + 'static&gt;(
    i1: I1::RefItem&lt;'a&gt;,
    i2: I2::RefItem&lt;'a&gt;,
) -&gt; bool
<span class="boring">}
</span></code></pre></pre>
<p>为了写出 i1, i2 的类型，不得不在 generic parameter 里面加一个 <code>'a</code>。就是这个 <code>'a</code> 成为了痛苦的根源。</p>
<p>如何抹掉这个生命周期呢？一拍脑袋能想到的办法就是用一个 trait 作为桥梁，抹平这个生命周期，并且证明 <code>cmp_ge</code> 对于所有生命周期都成立。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/// A trait over all scalar SQL functions.
///
/// It takes `A` and `B` as input prameter, and outputs scalar of type `O`.
pub trait BinaryExprFunc&lt;A: Scalar, B: Scalar, O: Scalar&gt; {
    /// Evaluate a binary function with two references to data.
    fn eval(&amp;self, i1: A::RefType&lt;'_&gt;, i2: B::RefType&lt;'_&gt;) -&gt; O;
}
<span class="boring">}
</span></code></pre></pre>
<p>这个 trait 的定义里面完全没有生命周期，这也意味着向量化的时候直接写：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;I1, I2, O, F&gt; BinaryExpression&lt;I1, I2, O, F&gt;
where
    O: Scalar,
    I1: Scalar,
    I2: Scalar,
    F: BinaryExprFunc&lt;I1, I2, O&gt;,
{
    // ...
}
<span class="boring">}
</span></code></pre></pre>
<p>即可。无需给 <code>F</code> 提供生命周期的参数，定义里面也不出现任何生命周期。</p>
<p>那么怎么证明 <code>BinaryExprFunc</code> 对于标量函数成立呢？比如我们能不能通过类似于宏展开的方法，做这样的事情：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl BinaryExprFunc for str_contains {
    // ...
}
<span class="boring">}
</span></code></pre></pre>
<p>这是不可能的。在 Rust 里，一个函数就是一个对象。它的类型是写不出来的。而 <code>impl Trait for Type</code> 的语法，要求最后这个位置是一个 Type。在这种情况下，我们只能做 blanket implementation：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/// Blanket implementation for all binary expression functions
impl&lt;A: Scalar, B: Scalar, O: Scalar, F&gt; BinaryExprFunc&lt;A, B, O&gt; for F
where
    F: Fn(A::RefType&lt;'_&gt;, B::RefType&lt;'_&gt;) -&gt; O,
{
    fn eval(&amp;self, i1: A::RefType&lt;'_&gt;, i2: B::RefType&lt;'_&gt;) -&gt; O {
        self(i1, i2)
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>为所有符合 <code>Fn(A::RefType&lt;'_&gt;, B::RefType&lt;'_&gt;) -&gt; O</code> 条件的标量函数都实现 <code>BinaryExprFunc</code>。</p>
<p>这么一个桥梁 trait 实现完以后，我们先验证一下已有的几个标量函数是否能够匹配上：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// 一个类似 str_contains 的函数
fn binary_str(_: &amp;str, _: &amp;str) -&gt; String {
    todo!()
}

// 一个类似 cmp_ge 的函数
fn binary_generics&lt;A: Scalar, B: Scalar, O: Scalar&gt;(_: A::RefType&lt;'_&gt;, _: B::RefType&lt;'_&gt;) -&gt; O {
    todo!()
}

// 用于验证一个函数是否 impl 某个 trait
fn test_if_impl&lt;A: Scalar, B: Scalar, O: Scalar, F: BinaryExprFunc&lt;A, B, O&gt;&gt;(_: F) {}

#[test]
fn test_simple_generics_function() {
    test_if_impl::&lt;i32, f32, i64, _&gt;(binary_generics::&lt;i32, f32, i64&gt;);
    test_if_impl::&lt;String, String, String, _&gt;(binary_str);
}
<span class="boring">}
</span></code></pre></pre>
<p>编译通过！说明我们的 trait <code>BinaryExprFunc</code> 架起了标量函数和向量化结构体的桥梁，证明了类似于 <code>cmp_ge</code> 的泛型函数对于<strong>所有生命周期</strong>都成立。接下来，向量化就好写多了。</p>
<h3 id="实现新的标量函数"><a class="header" href="#实现新的标量函数">实现新的标量函数</a></h3>
<p>回过来看 <code>cmp_ge</code>，它需要支持把用户输入的类型 cast 到新的类型以后再比较。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub fn cmp_ge&lt;I1: Scalar, I2: Scalar, C: Scalar&gt;(i1: I1::RefType&lt;'_&gt;, i2: I2::RefType&lt;'_&gt;) -&gt; bool
where
    /* ??? */
{
    i1.into().partial_cmp(&amp;i2.into()).unwrap() == Ordering::Greater
}
<span class="boring">}
</span></code></pre></pre>
<p>这里的 where bound 应该怎么写呢？有了之前写 HRTB 的经验，我们可以很方便地写出：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub fn cmp_ge&lt;I1: Scalar, I2: Scalar, C: Scalar&gt;(i1: I1::RefType&lt;'_&gt;, i2: I2::RefType&lt;'_&gt;) -&gt; bool
where
    for&lt;'a&gt; I1::RefType&lt;'a&gt;: Into&lt;C::RefType&lt;'a&gt;&gt;,
    for&lt;'a&gt; I2::RefType&lt;'a&gt;: Into&lt;C::RefType&lt;'a&gt;&gt;,
    for&lt;'a&gt; C::RefType&lt;'a&gt;: PartialOrd,
{
    i1.into().partial_cmp(&amp;i2.into()).unwrap() == Ordering::Greater
}
<span class="boring">}
</span></code></pre></pre>
<p>编译器又一次无情报错：</p>
<pre><code class="language-text">error[E0623]: lifetime mismatch
  --&gt; archive/day6-hard/src/expr/cmp.rs:42:8
   |
34 | pub fn cmp_ge&lt;I1: Scalar, I2: Scalar, C: Scalar&gt;(i1: I1::RefType&lt;'_&gt;, i2: I2::RefType&lt;'_&gt;) -&gt; bool
   |                                                      ---------------      --------------- these two types are declared with different lifetimes...
...
42 |     i1.into().partial_cmp(&amp;i2.into()).unwrap() == Ordering::Greater
   |        ^^^^ ...but data from `i2` flows into `i1` here
</code></pre>
<p>这是为什么捏？我们都证明了</p>
<ul>
<li>对于所有生命周期，I1 的引用可以转化为 C 的引用</li>
<li>对于所有生命周期，I2 的引用可以转化为 C 的引用</li>
<li>对于所有生命周期，C 实现了 PartialOrd</li>
</ul>
<p>等等，好像还差一步：不同生命周期的 C 应该如何比较？<code>I1::RefItem&lt;'_&gt;, I2::RefItem&lt;'_&gt;</code> 经过 desugar 以后实际上是：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub fn cmp_ge&lt;'a, 'b, I1: Scalar, I2: Scalar, C: Scalar&gt;(i1: I1::RefType&lt;'a&gt;, i2: I2::RefType&lt;'b&gt;) -&gt; bool
<span class="boring">}
</span></code></pre></pre>
<p>它们的生命周期是不一样的。而我们只证明了：</p>
<ul>
<li><code>I1::RefType&lt;'a&gt;: Into&lt;C::RefType&lt;'a&gt;&gt;</code> – I1 的引用可以转化为<strong>相同生命周期的</strong> C 的引用</li>
<li><code>I2::RefType&lt;'b&gt;: Into&lt;C::RefType&lt;'b&gt;&gt;</code> – I2 的引用可以转化为<strong>相同生命周期的</strong> C 的引用</li>
</ul>
<p>却没有证明：</p>
<ul>
<li><code>C::RefType&lt;'a&gt;: PartialOrd&lt;C::RefType&lt;'b&gt;&gt;</code> – 不同生命周期的 <code>C</code> 可以比较。</li>
</ul>
<p>这该怎么办捏？先试着用 HRTB 写一下 <code>for&lt;'a&gt; C::RefType&lt;'a&gt;: PartialOrd</code> 这个 bound。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub fn cmp_ge&lt;I1: Scalar, I2: Scalar, C: Scalar&gt;(i1: I1::RefType&lt;'_&gt;, i2: I2::RefType&lt;'_&gt;) -&gt; bool
where
    for&lt;'a&gt; I1::RefType&lt;'a&gt;: Into&lt;C::RefType&lt;'a&gt;&gt;,
    for&lt;'a&gt; I2::RefType&lt;'a&gt;: Into&lt;C::RefType&lt;'a&gt;&gt;,
    for&lt;'a, 'b&gt; C::RefType&lt;'a&gt;: PartialOrd&lt;C::RefType&lt;'b&gt;&gt;,
{
    i1.into().partial_cmp(&amp;i2.into()).unwrap() == Ordering::Greater
}
<span class="boring">}
</span></code></pre></pre>
<p>验证一下 <code>cmp_ge</code> 有没有匹配上 <code>BinaryExprFunc</code> 这个 bound：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn test_cmp_ge() {
    test_if_impl::&lt;i32, i64, bool, _&gt;(cmp_ge::&lt;i32, i64, i64&gt;);
    test_if_impl::&lt;String, String, bool, _&gt;(cmp_ge::&lt;String, String, String&gt;);
}
<span class="boring">}
</span></code></pre></pre>
<p>编译通过！</p>
<p>但如果要实现 <code>cmp_eq</code>，对于 <code>Eq</code> 这种 bound 怎么办捏？根据 <code>Eq</code> trait 的定义：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub trait Eq: PartialEq&lt;Self&gt; { }
<span class="boring">}
</span></code></pre></pre>
<p><code>Eq</code> 根本没有给我们提供指定 <code>Rhs</code> 的机会！这里直接写死了 <code>Rhs = Self</code>。这就意味着，我们必须找一种办法把 <code>i1</code> <code>i2</code> 两个变量的生命周期统一起来。这该怎么办？</p>
<p><em>注：实际上 PartialEq 是可以指定 Rhs 的，这里只是用类似于 Eq 这样的 trait 举个例子，毕竟有很多其他的 trait 是不提供 Rhs 的，但开发者往往会用到……</em></p>
<h3 id="协变与逆变"><a class="header" href="#协变与逆变">协变与逆变</a></h3>
<p>简单来说，如果我们写一个正常的函数：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn cmp_eq(i1: &amp;i32, i2: &amp;i32) -&gt; bool {
  i1 == i2
}
<span class="boring">}
</span></code></pre></pre>
<p>在 <code>i1 == i2</code> 的时候，编译器会自动把它们的生命周期统一。因为 <code>&amp;'a T</code> 关于 <code>'a</code> 是协变的 (covariant) (其他规则见 <a href="https://link.zhihu.com/?target=https%3A//doc.rust-lang.org/nomicon/subtyping.html">Subtyping and Variance - The Rustonomicon</a>)。因此，编译器在 <code>i1 == i2</code> 的地方把长的生命周期缩短，以让 <code>i1: &amp;i32, i2: &amp;i32</code> 符合 <code>PartialEq&lt;i32&gt;</code> 的签名：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub trait PartialEq&lt;Rhs = Self&gt; 
    fn eq(&amp;self, other: &amp;Rhs) -&gt; bool; // &amp;self 和 &amp;Rhs 生命周期需要**相同**
}
<span class="boring">}
</span></code></pre></pre>
<p>那么什么是逆变捏？举个例子：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn test_func&lt;'short&gt;(i1: &amp;'short i32, i2: &amp;'short i32) {}
<span class="boring">}
</span></code></pre></pre>
<p>调用 <code>test_func</code> 的时候，<code>i1</code> <code>i2</code> 的生命周期可能不同：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn another_test_func(outer: &amp;i32) {
    let val = 2333
    let inner = &amp;val;
    test_func(inner, outer);
}
<span class="boring">}
</span></code></pre></pre>
<p>此时 <code>inner</code> 的生命周期必然比 <code>outer</code> 短。编译器决定 <code>test_func</code> 的 <code>'short</code> 就是 <code>inner</code> 的生命周期，然后将长的生命周期 <code>outer</code> 变成短的。所以对于 <code>&amp;'long i32</code> 这个类型来说，它可以把生命周期变短，这叫协变；对于 <code>fn&lt;'short&gt;(&amp;'short i32, &amp;'short i32)</code> 来说，它可以接收生命周期比 <code>&amp;'short i32</code> 更长的变量，也就是将函数的签名变成 <code>fn&lt;'short, 'long: 'short&gt;(&amp;'short i32, &amp;'long i32)</code>。这就叫逆变。</p>
<p>以上分析纯属我瞎扯，具体编译器是怎么实现的请阅读 <a href="https://link.zhihu.com/?target=https%3A//rustc-dev-guide.rust-lang.org/variance.html">Variance of type and lifetime parameters - Guide to Rustc Development</a>。我不是类型论专家，上面可能有口误之处，见谅。</p>
<p>协变和逆变都解释完了，这和 GAT 又有什么关系捏？</p>
<h3 id="实现-gat-的生命周期转化"><a class="header" href="#实现-gat-的生命周期转化">实现 GAT 的生命周期转化</a></h3>
<p>回到 <code>Scalar</code> trait 的声明。对于 GAT 类型 <code>RefType</code> 来说：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub trait Scalar /* 省略 */ {
    type RefType&lt;'a&gt; /* 省略 bound */;
}
<span class="boring">}
</span></code></pre></pre>
<p><code>i32::RefType&lt;'short&gt;</code> 和 <code>i32::RefType&lt;'long&gt;</code> 之间是不能自动转换的：GAT 类型不是协变的！</p>
<p>这就意味着我们要手动实现生命周期之间的转换。根据 <a href="https://link.zhihu.com/?target=https%3A//internals.rust-lang.org/t/variance-of-lifetime-arguments-in-gats/14769/19">dtolnay 大佬的建议</a>，我们给 <code>Scalar</code> 加上一个 <code>upcast_gat</code> 函数：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub trait Scalar /* ... */ {
    /* ... */
    fn upcast_gat&lt;'short, 'long: 'short&gt;(long: Self::RefType&lt;'long&gt;) -&gt; Self::RefType&lt;'short&gt;;
}
<span class="boring">}
</span></code></pre></pre>
<p>这样一来，我们就可以在泛型函数里把 <code>Scalar::RefType&lt;'long&gt;</code> 转换为 <code>Scalar::RefType&lt;'short&gt;</code> 了，相当于手动实现了 GAT 关于生命周期的协变。</p>
<p>随手 impl 一下各个类型的 <code>upcast_gat</code>：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl Scalar for String {
    fn upcast_gat&lt;'short, 'long: 'short&gt;(long: &amp;'long str) -&gt; &amp;'short str {
        long
    }
}

impl Scalar for $Owned {
    fn upcast_gat&lt;'short, 'long: 'short&gt;(long: $Owned) -&gt; $Owned {
        long
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>现在就可以自如转换了！</p>
<h3 id="重新实现新的标量函数"><a class="header" href="#重新实现新的标量函数">重新实现新的标量函数</a></h3>
<p>有了 <code>upcast_gat</code> 之后，<code>PartialOrd</code> 的 bound 就不用把 <code>Rhs</code> 写出来了：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub fn cmp_ge&lt;I1: Scalar, I2: Scalar, C: Scalar&gt;(i1: I1::RefType&lt;'_&gt;, i2: I2::RefType&lt;'_&gt;) -&gt; bool
where
    for&lt;'a&gt; I1::RefType&lt;'a&gt;: Into&lt;C::RefType&lt;'a&gt;&gt;,
    for&lt;'a&gt; I2::RefType&lt;'a&gt;: Into&lt;C::RefType&lt;'a&gt;&gt;,
    for&lt;'a&gt; C::RefType&lt;'a&gt;: PartialOrd,
{
    let i1 = I1::upcast_gat(i1);
    let i2 = I2::upcast_gat(i2);
    i1.into().partial_cmp(&amp;i2.into()).unwrap() == Ordering::Greater
}
<span class="boring">}
</span></code></pre></pre>
<p>这样我们就实现了基于 GAT 手动协变的标量泛型函数。</p>
<h3 id="实现真正的表达式向量化"><a class="header" href="#实现真正的表达式向量化">实现真正的表达式向量化</a></h3>
<p>有了 <code>BinaryExprFunc</code> 之后，标量函数的生命周期就全部抹掉了。直接用 <code>BinaryExprFunc</code> 来写 <code>BinaryExpression</code> 里面的 <code>func: F</code> 类型。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;I1, I2, O, F&gt; BinaryExpression&lt;I1, I2, O, F&gt;
where
    O: Scalar,
    I1: Scalar,
    I2: Scalar,
    for&lt;'a&gt; &amp;'a I1::ArrayType: TryFrom&lt;&amp;'a ArrayImpl, Error = TypeMismatch&gt;,
    for&lt;'a&gt; &amp;'a I2::ArrayType: TryFrom&lt;&amp;'a ArrayImpl, Error = TypeMismatch&gt;,
    F: BinaryExprFunc&lt;I1, I2, O&gt;,
{
    pub fn new(func: F) -&gt; Self {
        Self {
            func,
            _phantom: PhantomData,
        }
    }

    /// Evaluate the expression with the given array.
    pub fn eval_batch(&amp;self, i1: &amp;ArrayImpl, i2: &amp;ArrayImpl) -&gt; Result&lt;ArrayImpl&gt; {
        let i1a: &amp;I1::ArrayType = i1.try_into()?;
        let i2a: &amp;I2::ArrayType = i2.try_into()?;
        assert_eq!(i1.len(), i2.len(), &quot;array length mismatch&quot;);
        let mut builder = &lt;O::ArrayType as Array&gt;::Builder::with_capacity(i1.len());
        for (i1, i2) in i1a.iter().zip(i2a.iter()) {
            match (i1, i2) {
                (Some(i1), Some(i2)) =&gt; builder.push(Some(self.func.eval(i1, i2).as_scalar_ref())),
                _ =&gt; builder.push(None),
            }
        }
        Ok(builder.finish().into())
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>性质都全了，这个程序一定能编译通过吧！然后我们又无情被编译器打脸。</p>
<pre><code class="language-text">error[E0308]: mismatched types
  --&gt; archive/day6-hard/src/expr/vectorize.rs:72:74
   |
72 |                 (Some(i1), Some(i2)) =&gt; builder.push(Some(self.func.eval(i1, i2).as_scalar_ref())),
   |                                                                          ^^ expected scalar::Scalar::RefType, found array::Array::RefItem
   |
   = note: expected associated type `&lt;I1 as scalar::Scalar&gt;::RefType&lt;'_&gt;`
              found associated type `&lt;&lt;I1 as scalar::Scalar&gt;::ArrayType as array::Array&gt;::RefItem&lt;'_&gt;`

error[E0308]: mismatched types
  --&gt; archive/day6-hard/src/expr/vectorize.rs:72:78
   |
72 |                 (Some(i1), Some(i2)) =&gt; builder.push(Some(self.func.eval(i1, i2).as_scalar_ref())),
   |                                                                              ^^ expected scalar::Scalar::RefType, found array::Array::RefItem
   |
   = note: expected associated type `&lt;I2 as scalar::Scalar&gt;::RefType&lt;'_&gt;`
              found associated type `&lt;&lt;I2 as scalar::Scalar&gt;::ArrayType as array::Array&gt;::RefItem&lt;'_&gt;`

error[E0308]: mismatched types
  --&gt; archive/day6-hard/src/expr/vectorize.rs:72:59
   |
72 |                 (Some(i1), Some(i2)) =&gt; builder.push(Some(self.func.eval(i1, i2).as_scalar_ref())),
   |                                                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected array::Array::RefItem, found scalar::Scalar::RefType
   |
   = note: expected associated type `&lt;&lt;O as scalar::Scalar&gt;::ArrayType as array::Array&gt;::RefItem&lt;'_&gt;`
              found associated type `&lt;O as scalar::Scalar&gt;::RefType&lt;'_&gt;`

For more information about this error, try `rustc --explain E0308`.
</code></pre>
<p>编译器一连报了三个错，我们来看看：</p>
<p>前两个错大概是：</p>
<pre><code class="language-text">= note: expected associated type `&lt;I1 as scalar::Scalar&gt;::RefType&lt;'_&gt;`
              found associated type `&lt;&lt;I1 as scalar::Scalar&gt;::ArrayType as array::Array&gt;::RefItem&lt;'_&gt;`
</code></pre>
<p>也就是编译器不能证明 <code>I1::ArrayType::RefItem</code> 就是 <code>I1::RefType</code>。第二个错同理。</p>
<p>第三个错是：</p>
<pre><code class="language-text">= note: expected associated type `&lt;&lt;O as scalar::Scalar&gt;::ArrayType as array::Array&gt;::RefItem&lt;'_&gt;`
              found associated type `&lt;O as scalar::Scalar&gt;::RefType&lt;'_&gt;`
</code></pre>
<p>编译器不能证明 <code>O::RefType</code> 就是 <code>O::ArrayType::RefItem</code>。和之前的两个错转换方向相反。</p>
<p>这还不简单？我们之前已经做过无数次类似的类型体操了。可以用 HRTB 把 bound 写在 <code>BinaryExpression</code> 上。</p>
<p>先正着写：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;I1, I2, O, F&gt; BinaryExpression&lt;I1, I2, O, F&gt;
where
    /* ... */
    for&lt;'a&gt; I1::ArrayType: Array&lt;RefItem&lt;'a&gt; = I1::RefType&lt;'a&gt;&gt;,
    for&lt;'a&gt; I2::ArrayType: Array&lt;RefItem&lt;'a&gt; = I2::RefType&lt;'a&gt;&gt;,
    for&lt;'a&gt; O::ArrayType: Array&lt;RefItem&lt;'a&gt; = O::RefType&lt;'a&gt;&gt;,
{
<span class="boring">}
</span></code></pre></pre>
<p>编译失败，要在各种地方加 trait；再换个 trait 写：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;I1, I2, O, F&gt; BinaryExpression&lt;I1, I2, O, F&gt;
where
    /* ... */
    for&lt;'a&gt; I1: Scalar&lt;RefType&lt;'a&gt; = &lt;I1::ArrayType as Array&gt;::RefItem&lt;'a&gt;&gt;,
    for&lt;'a&gt; I2: Scalar&lt;RefType&lt;'a&gt; = &lt;I2::ArrayType as Array&gt;::RefItem&lt;'a&gt;&gt;,
    for&lt;'a&gt; O: Scalar&lt;RefType&lt;'a&gt; = &lt;O::ArrayType as Array&gt;::RefItem&lt;'a&gt;&gt;,
{
<span class="boring">}
</span></code></pre></pre>
<p>报错逐渐离谱：</p>
<pre><code class="language-text">error[E0391]: cycle detected when computing the bounds for type parameter `I1`
  --&gt; archive/day6-hard/src/expr/vectorize.rs:52:39
   |
52 |     for&lt;'a&gt; I1: Scalar&lt;RefType&lt;'a&gt; = &lt;I1::ArrayType as Array&gt;::RefItem&lt;'a&gt;&gt;,
   |                                       ^^^^^^^^^^^^^
   |
   = note: ...which immediately requires computing the bounds for type parameter `I1` again
note: cycle used when computing explicit predicates of `expr::vectorize::&lt;impl at archive/day6-hard/src/expr/vectorize.rs:44:1: 81:2&gt;`
  --&gt; archive/day6-hard/src/expr/vectorize.rs:49:17
   |
49 |     for&lt;'a&gt; &amp;'a I1::ArrayType: TryFrom&lt;&amp;'a ArrayImpl, Error = TypeMismatch&gt;,
   |                 ^^^^^^^^^^^^^
</code></pre>
<p>总之在这里写 HRBT 是写不出来的。那怎么办捏？</p>
<p>就在几分钟前，我们通过 <code>upcast_gat</code> 实现了生命周期的协变。这里能不能也用类似的方法解决呢？</p>
<p>拍了拍脑袋，直接给 <code>Scalar</code> 加一个 <code>Scalar::ArrayType::RefItem</code> 与 <code>Scalar::RefType</code> 之间互相转换的函数吧：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub trait Scalar {
    /// Cast `Scalar::RefType` to `Array::RefItem`.
    ///
    /// This function will only be used in internal implementation of `BinaryExpression`, so we
    /// don't give a meaningful name to this function.
    #[allow(clippy::needless_lifetimes)]
    fn cast_s_to_a&lt;'x&gt;(item: Self::RefType&lt;'x&gt;) -&gt; &lt;Self::ArrayType as Array&gt;::RefItem&lt;'x&gt;;

    /// Cast `Array::RefItem` to `Scalar::RefType`
    ///
    /// This function will only be used in internal implementation of `BinaryExpression`, so we
    /// don't give a meaningful name to this function.
    #[allow(clippy::needless_lifetimes)]
    fn cast_a_to_s&lt;'x&gt;(item: &lt;Self::ArrayType as Array&gt;::RefItem&lt;'x&gt;) -&gt; Self::RefType&lt;'x&gt;;
}
<span class="boring">}
</span></code></pre></pre>
<p><em>注：这里碰到了 clippy 的 bug，要我把</em> <em><code>'x</code></em> <em>这个 lifetime 去掉，但实际上是去不掉的。</em></p>
<p>简单给每个 Scalar 类型都实现一下这两个函数，最后改一下 <code>eval_batch</code>：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>for (i1, i2) in i1a.iter().zip(i2a.iter()) {
    match (i1, i2) {
        (Some(i1), Some(i2)) =&gt; builder.push(Some(O::cast_s_to_a(
            self.func
                .eval(I1::cast_a_to_s(i1), I2::cast_a_to_s(i2))
                .as_scalar_ref(),
        ))),
        _ =&gt; builder.push(None),
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>我们用 <code>cast_a_to_s</code>, <code>cast_s_to_a</code> 这两个黑魔法打败了编译器。</p>
<p>于是，编译通过，向量化也完成了！这个系列类型体操做法的好处是，开发者只要写一个裸的函数，直接就可以被向量化。</p>
<h3 id="实现-boxedexpression"><a class="header" href="#实现-boxedexpression">实现 BoxedExpression</a></h3>
<p>生命周期都被抹掉以后，<code>BoxedExpression</code> 也更好实现了：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/// A trait over all expressions -- unary, binary, etc.
pub trait Expression {
    /// Evaluate an expression with run-time number of [`ArrayImpl`]s.
    fn eval_expr(&amp;self, data: &amp;[&amp;ArrayImpl]) -&gt; Result&lt;ArrayImpl&gt;;
}

/// All supported expression functions
pub enum ExpressionFunc {
    CmpLe,
    CmpGe,
    CmpEq,
    CmpNe,
    StrContains,
}

/// Build expression with runtime information.
pub fn build_binary_expression(f: ExpressionFunc) -&gt; Box&lt;dyn Expression&gt; {
    use ExpressionFunc::*;

    use crate::expr::cmp::*;
    use crate::expr::string::*;
    use crate::expr::vectorize::*;

    match f {
        CmpLe =&gt; Box::new(BinaryExpression::&lt;i32, i32, bool, _&gt;::new(
            cmp_le::&lt;i32, i32, i64&gt;,
        )),
        CmpGe =&gt; Box::new(BinaryExpression::&lt;i32, i32, bool, _&gt;::new(
            cmp_ge::&lt;i32, i32, i64&gt;,
        )),
        CmpEq =&gt; Box::new(BinaryExpression::&lt;i32, i32, bool, _&gt;::new(
            cmp_eq::&lt;i32, i32, i64&gt;,
        )),
        CmpNe =&gt; Box::new(BinaryExpression::&lt;i32, i32, bool, _&gt;::new(
            cmp_ne::&lt;i32, i32, i64&gt;,
        )),
        StrContains =&gt; Box::new(BinaryExpression::&lt;String, String, bool, _&gt;::new(
            str_contains,
        )),
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>我们可以把 <code>BinaryExpression</code> 做成 <code>Box&lt;dyn Expression&gt;</code>，之后就可以在函数里构建，然后到处传递了。再给 <code>BinaryExpression</code> 实现 <code>Expression</code> trait：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>/// [`Expression`] implementation for [`BinaryExpression`]
impl&lt;I1, I2, O, F&gt; Expression for BinaryExpression&lt;I1, I2, O, F&gt;
where
    O: Scalar,
    I1: Scalar,
    I2: Scalar,
    for&lt;'a&gt; &amp;'a I1::ArrayType: TryFrom&lt;&amp;'a ArrayImpl, Error = TypeMismatch&gt;,
    for&lt;'a&gt; &amp;'a I2::ArrayType: TryFrom&lt;&amp;'a ArrayImpl, Error = TypeMismatch&gt;,
    F: BinaryExprFunc&lt;I1, I2, O&gt;,
{
    fn eval_expr(&amp;self, data: &amp;[&amp;ArrayImpl]) -&gt; Result&lt;ArrayImpl&gt; {
        if data.len() != 2 {
            return Err(anyhow!(&quot;Expect two inputs for BinaryExpression&quot;));
        }
        self.eval_batch(data[0], data[1])
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>终于，我们得到了一个真正的表达式向量化框架：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[test]
fn test_build_str_contains() {
    let expr = build_binary_expression(ExpressionFunc::StrContains);

    for _ in 0..10 {
        let result = expr
            .eval_expr(&amp;[
                &amp;StringArray::from_slice(&amp;[Some(&quot;000&quot;), Some(&quot;111&quot;), None]).into(),
                &amp;StringArray::from_slice(&amp;[Some(&quot;0&quot;), Some(&quot;0&quot;), None]).into(),
            ])
            .unwrap();
        assert_eq!(result.get(0).unwrap(), ScalarRefImpl::Bool(true));
        assert_eq!(result.get(1).unwrap(), ScalarRefImpl::Bool(false));
        assert!(result.get(2).is_none());
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>Day 6 总算结束了！</p>
<p>上篇：<a href="https://zhuanlan.zhihu.com/p/461657165">数据库表达式执行的黑魔法：用 Rust 做类型体操 (Part 3 &amp; 4)</a></p>
<p>下篇：<a href="https://zhuanlan.zhihu.com/p/463477290">数据库表达式执行的黑魔法：与 Rust 编译器斗智斗勇 (Part 7)</a></p>
<p>您可以在 <a href="https://link.zhihu.com/?target=https%3A//github.com/skyzh/type-exercise-in-rust">type-exercise-in-rust</a> 中围观整个系统的实现。</p>
<p><em>（系列文章持续更新中，下一次更新时间看心情）</em></p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码_Part_3_&amp;_4.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>

                            <a rel="next" href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型_Part_7.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码_Part_3_&amp;_4.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>

                    <a rel="next" href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型_Part_7.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>




        <script type="text/javascript">
            window.playground_copyable = true;
        </script>


        <script src="../../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../searcher.js" type="text/javascript" charset="utf-8"></script>

        <script src="../../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->


    </body>
</html>
